package com.study.hot.jetpack.room.test_address

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.study.hot.R
import com.study.hot.jetpack.room.test_address.db.Address
import com.study.hot.jetpack.room.test_address.repository.AddressRepository
import com.study.hot.jetpack.room.test_address.viewmodel.AddAdressViewModel
import kotlinx.android.synthetic.main.add_adress_fragment.*
import org.jetbrains.anko.sdk27.coroutines.onClick

class AddAdressFragment : Fragment() {


    companion object {
        fun newInstance() = AddAdressFragment()
    }

    private lateinit var viewModel: AddAdressViewModel
    lateinit var mContext: Context

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.add_adress_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(AddAdressViewModel::class.java)
        addressAddBtn.onClick {
            val city = addressCityEt.text.toString()
            val area = addressAreaEt.text.toString()
            AddressRepository.newInstance(mContext).addressDao.insert(Address(null, city, area))
            val controller = Navigation.findNavController(requireView())
            controller.navigate(R.id.action_addAdressFragment_to_addressFragment)
        }
    }

}
